const multer = require('koa-multer');
const fs = require("fs");
const path = require("path");
//加载koa-multer模块
//文件上传
//配置
let storage = multer.diskStorage({

    //文件保存路径
    destination: function (req, file, cb) {
        let basedir = 'public/uploads/';
        //if(fs.mkdir)
        let date = new Date();
        let data = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
        basedir += data;
        mkdirsSync(basedir,{recursive: true});
        cb(null, basedir);
    },
    //修改文件名称
    filename: function (req, file, cb) {
        let fileFormat = (file.originalname).split(".");

        cb(null, Date.now() + "." + fileFormat[fileFormat.length - 1]);
    }
});
//递归创建目录 同步方法
function mkdirsSync(dirname, mode){
    console.log(dirname);
    if(fs.existsSync(dirname)){
        return true;
    }else{
        if(mkdirsSync(path.dirname(dirname), mode)){
            fs.mkdirSync(dirname, mode);
            return true;
        }
    }
    console.log("目录创建成功。");
}
//加载配置
let upload = multer({storage: storage});
module.exports = upload;